import { reactive, provide, ref, nextTick, watchEffect, watch, inject } from "vue";
import { useRoute, useRouter } from "vue-router";
import _ from 'lodash';
import { Message } from "@arco-design/web-vue";
import * as Store from "@/store";
import * as Api from "@/api/processClient/processClient";
import type * as StoreType from "@/store/modules/processHeader/type";
import type * as PageType from '../index.d';
import type * as ApiType from '@/api/processClient/processClient.d';


interface CallBack {
  flag: boolean;
  status: string;
}

interface CallBackData {
  done(closed: boolean): void | boolean | Promise<void | boolean>;
  flag: boolean;
  status: string;
}

const useContatiner = (setColor: Function) => {
  const router = useRouter();
  const route = useRoute();
  const PrData = Store.useProcessData();
  const data: PageType.ViewData = reactive({
    headerTitle: "",
    isQuery: route.query.type === "view" && route.query.viewType === 'all',
    isSumbit: route.query.type !== "view",
    disabled: route.query.type === "view",
    seiesId: "",
    lesionList: [] as StoreType.Lesion[],
    // 右侧是否展示废片
    isReject: false,
    rejectValue: "",
    // 右侧是否展示阴阳性
    isYay: false,
    yayValue: false,
    // 工具展示阴阳性
    isShowYay: false,
    yay: (undefined as unknown) as boolean,
    seriesVisible: true,
    signForm: {} as StoreType.Sign,
    submitVisible: false,
    sectionVisible: false,
    lesionVisible: false,
  });
  const btnData = reactive({
    btnFrom: '',
  });
  const formRef:any = reactive({
    seriesSetClass: 'seriesForm',
  })

  // 设置当前小征象
  const getLesionSign = (type: boolean, result?: any) => {
    data.seriesVisible = !type;
    if (type) {
      // true 小征象
      data.signForm = result.currentItem.lesion.signForm;
    } else {
      // false 大征象
      data.signForm = PrData.bigSignObj;
    };
  };
 
  // 内部组件抛出的表单操作事件及位置审核操作事件
  const handleChange = async (e: any) => {
    if (e.type) {
      // 通过仓库字典及当前表单对象获取病灶id集合
      const list: ApiType.AuditTaskImageResultList[] = PrData.imageGroupMap.get(data.signForm.formId);
      const imageIdList = list.map(item => item.imageId);
      // 根据所有类型数据集合及当前表单对象获取当前操作的表单
      const typeList = PrData.lesionResultList.filter(item => item.id === data.signForm.lesionType)[0];
      const current = typeList.viewList.filter(item => item.lesionData.imageGroupId === data.signForm.formId)[0];
      // 同时更新全部数据
      const allTypeList = PrData.dataList[0].children.filter(item => item.id === data.signForm.lesionType)[0];
      const allCurrent = allTypeList.viewList.filter(item => item.lesionData.imageGroupId === data.signForm.formId)[0];
      // 操作位置审核
      const params = {
        expectResultType: e.value,
        imageIdList
      };
      const posResult = await Api.savePosition(params);
      if (!posResult.data) {
        if (current.lesionData.approveStatus === 1) {
          const statusParams = {
            imageIdList,
            auditStatus: 2
          };
          const status = await Api.updateLesionStatus(statusParams);
          if (!status.data) {
            // 接口成功改变状态
            current.lesionData.approveStatus = 2;
            current.lesionData.positionVal = e.value;
            current.lesion.signForm.positionVal = e.value;
            allCurrent.lesionData.approveStatus = 2;
            allCurrent.lesionData.positionVal = e.value;
          };
          // 循环当前的表单对象集合并将待审核状态病灶同时存储当前小征象表单数据
          Object.getOwnPropertyNames(e.seriesSettings.form).map(async (key) => {
            const formParams = {
              formComponentId: +key,
              result: e.seriesSettings.form[key],
              imageId: current.lesionData.approveLeisonId
            };
            e.seriesSettings.formOptions.map((item: { id: number; type: string; }) => {
              if (item.id === +key && item.type === 'checkbox') {
                formParams.result = formParams.result.join(',');
              }
              if (item.id === +key && item.type === 'child_select') {
                formParams.result = formParams.result.join('@#@');
              }
            })
            const result = await Api.saveMinSign(formParams);
            if (result.data) {
              current.lesion.signForm.form = _.cloneDeep({
                ...current.lesion.signForm.form,
                ...e.seriesSettings.form
              })
            };
          });
        };
        allCurrent.lesionData.positionVal = e.value;
        current.lesionData.positionVal = e.value;
        current.lesion.signForm.positionVal = e.value;
      };
    } else {
      // 操作征象表单
      if (e.signType) {
        // 审核大征象
        const params = {
          componentResultList: [] as {componentId: number, result: string}[],
          sarId: PrData.sarIdList[PrData.index]
        };
        params.componentResultList = data.signForm.formOptions.map(item => {
          let result = '';
          if (Array.isArray(data.signForm.form[item.id])) {
            if (item.type === 'checkbox') {
              result = (data.signForm.form[item.id] as string[]).join(',');
            };
            if (item.type === 'child_select') {
              result = (data.signForm.form[item.id] as string[]).join('@#@');
            };
          } else {
            result = data.signForm.form[item.id] as string;
          };
          return {
            componentId: item.id,
            result
          };
        });
        const result = await Api.saveBigSign(params);
        if (result.data) {
          data.signForm.formOptions && data.signForm.formOptions.map(item => {
            PrData.dataList[0].seriesCompList.form[item.id] = data.signForm.form[item.id];
          });
        };
      } else {
        // 获取当前病灶id
        let list:any = [];
        if (data.signForm.lesionType !== 4) {
          list = PrData.imageGroupMap.get(data.signForm.formId);
        } else {
          const tempArr = PrData.lesionResultList.filter(item => item.id === data.signForm.lesionType)[0];
          list = tempArr.lesionList;
        };
        // 审核小征象
        const params:any = {
          formComponentId: e.value.item.id, 
          result: e.value.value, 
          imageId: 0
        };
        if (e.value.item.type === 'checkbox' && e.value.value.length !== 0) {
          params.result = params.result.join(',');
        }
        if (e.value.item.type === 'checkbox' && e.value.value.length === 0) {
          params.result = '';
        }
        if (e.value.item.type === 'child_select' && e.value.value.length !== 0) {
          params.result = params.result.join('@#@');
        };
        if (e.value.item.type === 'child_select' && e.value.value.length === 0) {
          params.result = '';
        }
        if (e.value.item.lesionType === 1 || e.value.item.lesionType === 2) {
          params.imageId = list[2].imageId;
        };
        if (e.value.item.lesionType === 3) {
          params.imageId = list[1].imageId;
        };
        if (e.value.item.lesionType === 4) {
          const currentList = list.filter((item: { imageGroupId: number; }[]) => item[0].imageGroupId === data.signForm.formId)[0];
          params.imageId = currentList[0].imageId;
        };
        const result = await Api.saveMinSign(params);
        if (result.data) {
          PrData.lesionResultList.map(item => {
            if (item.id === data.signForm.lesionType) {
              item.viewList.length !== 0 && item.viewList.map(it => {
                if (it.lesionData.imageGroupId === data.signForm.formId) {
                  // 找到当前的表单项
                  it.lesion.signForm.form = _.cloneDeep({
                    ...it.lesion.signForm.form,
                    ...data.signForm.form
                  });
                };
              });
              // 通过当前过滤出的集合的viewList找出当前的表单项
              item.lesionList.length !== 0 && item.lesionList.map(it => {
                it.map(t => {
                  if (t.imageGroupId === data.signForm.formId) {
                    t.formComponentList && t.formComponentList.map(i => {
                      if (i.formComponentId === result.data.formComponentId) {
                       i.result = result.data.result; 
                      };
                    });
                  };
                });
              });
            };
          });
        };
      };
    };
  };

  // 调用接口操作
  const handleInterface = async (result: any) => {
    if (result.type === "reject") {
      const params = {
        sarIdList: PrData.sarIdList.join(","),
        discardCode: result.form.scrapValue,
        discardReason: result.form.discardRemark,
      };
      const apiResult = await Api.saveReject(params);
      data.submitVisible = true;
    };
    if (result.type === "yay") {
      data.yay = result.value;
      const params = {
        sarIdList: PrData.sarIdList.join(","),
        yayAttributes: result.value ? 1 : 2,
      };
      const apiResult = await Api.updateYay(params);
    };
  };

  // 最终提交取消按钮点击
  const handleCancel = () => {
    data.submitVisible = false;
  };

  // 最终提交并操作
  const handleSubmitVisible = (logData: CallBack) => {
    if (btnData.btnFrom === 'reject') {
      getSubmitInterface(logData);
    } else {
      getYaYStatus(logData);
    };
    // data.submitVisible = logData.flag;
  };

  // 最终无切片确认
  const handleSectionVisible = (logData: CallBackData) => {
    if (logData.status === 'save') {
      logData.done(true);
      data.sectionVisible = logData.flag;
      if( route.query.type === 'create' ){
        window.location.href = `${location.origin}/#!/personalaccount`;
      } else {
        router.back();
        // window.location.href = `${location.origin}/#!/taskdetail/${route.query.taskId}/editor`;
      };
    } else {
      data.sectionVisible = logData.flag;
    };
  };

  // 还有待审核的病灶弹窗操作
  const handleLesionVisible = (logData: CallBackData) => {
    if (logData.status === 'save') {
      logData.done(true);
    };
    data.lesionVisible = logData.flag;
  };

  // 查询是否还存在待审核病灶
  const getAuditLesion = () => {
    let auditStatus = false;
    PrData.lesionResultList.map(item => {
      item.viewList.map(it => {
        if (it.lesionData.approveStatus === 1) {
          auditStatus = true;
        };
      });
    });
    if (auditStatus) {
      data.lesionVisible = true;
    } else {
      data.submitVisible = true;
    };
  };

  // 校验选择阴阳性
  const getYaYStatus = (logData: CallBack) => {
    if (data.isShowYay) {
      // 需要阴阳性
      if (data.yay === undefined && data.isShowYay) {
        Message.warning({
          content: '请选择阴阳性！',
          closable: true,
          duration: 3000,
        });
        data.submitVisible = logData.flag;
      } else {
        // 阴阳性通过
        getBigSignStatus(logData);
      };
    } else {
      // 不需要阴阳性
      getBigSignStatus(logData);
    };
  };

  // 校验大征象是否填写
  const getBigSignStatus = (logData: CallBack) => {
    let flag = true;
    PrData.dataList.forEach(item => {
      if (!flag) return;
      item.seriesCompList.formOptions.forEach(it => {
        if (!flag) return;
        if (it.lesionType !== 4) {
          if (item.seriesCompList.form[it.id] === '' || item.seriesCompList.form[it.id].length === 0) {
            Message.warning({
              content: '请将序列征象必填项填写完整！',
              closable: true,
              duration: 3000,
            });
            const fileds = <{[x: string]: any}>{};
            fileds[it.approveField] = {
              status: 'error',
              message: `${it.name}不可为空！`
            }
            nextTick(() => {
              formRef.seriesForm.setFields({
                [it.approveField]: {...fileds[it.approveField]}
              });
            })
            flag = false;
            data.submitVisible = logData.flag;
            // 大征象错误聚焦
            // PrData.getIncreaseCurrent();
            // 大征象错误聚焦
            PrData.lesionResultList && PrData.lesionResultList.map(it => {
              it.isVisible = false;
              it.viewList.map(t => {
                t.lesionData.isCurrent = false;
              });
            });
            getLesionSign(false);
          }
        } else {
          if (it.required && (item.seriesCompList.form[it.id] === '' || item.seriesCompList.form[it.id].length === 0)) {
            Message.warning({
              content: '请将序列征象必填项填写完整！',
              closable: true,
              duration: 3000,
            });
            const fileds = <{[x: string]: any}>{};
            fileds[it.approveField] = {
              status: 'error',
              message: `${it.name}不可为空！`
            }
            flag = false;
            data.submitVisible = logData.flag;
            // 大征象错误聚焦
            // PrData.getIncreaseCurrent();
            // 大征象错误聚焦
            PrData.lesionResultList && PrData.lesionResultList.map(it => {
              it.isVisible = false;
              it.viewList.map(t => {
                t.lesionData.isCurrent = false;
              });
            });
            getLesionSign(false);
            nextTick(() => {
              formRef.seriesForm.setFields({
                [it.approveField]: {...fileds[it.approveField]}
              });
            })
          };
        };
      });
    });
    if (flag) {
      getSmaleSignStatus(logData);
    };
  };

  // 校验小征象位置错误时候表单是否填写
  const getSmaleSignStatus = (logData: CallBack) => {
    let flag = true;
    PrData.lesionResultList.forEach(ite => {
      ite.isVisible = false;
      if (!flag) return;
      ite.viewList.forEach(it => {
        it.lesionData.isCurrent = false;
        if (!flag) return;
        if (it.lesionData.positionVal === 1) {
          it.lesion.signForm.formOptions.forEach(t => {
            if (!flag) return;
            if (it.lesion.signForm.form[t.id] === '' || it.lesion.signForm.form[t.id].length === 0) {
              Message.warning({
                content: '请将征象必填项填写完整！',
                closable: true,
                duration: 3000,
              });
              const fileds = <{[x: string]: any}>{};
              fileds[t.approveField] = {
                status: 'error',
                message: `${t.name}不可为空！`
              }
              flag = false;
              data.submitVisible = logData.flag;
              // 小征象错误聚焦
              ite.isVisible = true;
              it.lesionData.isCurrent = true;
              getLesionSign(true, {currentItem: it});
              const activeColor = "#008000";
              const defaultColor = "#fbb03b";
              const currentActiveColor = it.lesionData.isCurrent ? activeColor : defaultColor;
              setColor(it.lesionData.toolType, it.lesionData.uuid, currentActiveColor, defaultColor);
              nextTick(() => {
                formRef.seriesForm.setFields({
                  [t.approveField]: {...fileds[t.approveField]}
                });
              })
            };
          });
        };
      });
    });
    if (flag) {
      getSubmitInterface(logData);
    };
  };

  // 最终调用保存接口
  const getSubmitInterface = async (logData: CallBack) => {
    // 全部通过调用保存接口
    if (btnData.btnFrom !== 'reject') {
      data.submitVisible = logData.flag;
      const submitParams = {
        sarIdList: PrData.sarIdList.join(',')
      };
      const result = await Api.saveData(submitParams);
    };
    if (route.query.type === 'edit') {
      // 关闭
      // window.location.href = `${location.origin}/#!/taskdetail/${route.query.taskId}/editor`;
      router.back();
    } else {
      if (logData.status === 'more') {
        // 切换新序列
        const params = {
          userId: PrData.userId,
          taskId: PrData.taskId,
        };
        const seriesResult = await Api.getSeries(params);
        if (!seriesResult.data) {
          data.sectionVisible = true;
        } else {
          router.go(0);
        };
      } else {
        // 关闭
        router.back();
        // window.location.href = `${location.origin}/#!/taskdetail/${route.query.taskId}/editor`;
      };
    }
  };

  return reactive({
    compData: data,
    btnData,
    formRef,
    handleInterface,
    handleChange,
    handleCancel,
    handleSubmitVisible,
    handleSectionVisible,
    handleLesionVisible,
    getAuditLesion,
    getLesionSign,
    getSubmitInterface
  });
}

export default useContatiner;